package file.server

import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString

@EqualsAndHashCode(includes = 'username')
@ToString(includes = 'username', includeNames = true, includePackage = false)
class User implements Serializable
{
    private static final long serialVersionUID = 1

    transient springSecurityService

    String code
    String username
    String password
    String fullName
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired
    String cellphone
    String externalId
    String appSessionId
    String avatarUrl
    String verificationCode
    Boolean loginBySms = false

    User(String username, String password)
    {
        this()
        this.username = username
        this.password = password
    }

    Set<Role> getAuthorities()
    {
        UserRole.findAllByUser(this)*.role
    }

    def beforeInsert()
    {
        code = cellphone
        encodePassword()
    }

    def beforeUpdate()
    {
        code = cellphone
        if (isDirty('password'))
        {
            encodePassword()
        }
    }

    protected void encodePassword()
    {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
    }

    static transients = ['springSecurityService']

    static constraints = {
        password blank: false, password: true
        username blank: false, unique: true
        code blank: true, nullable: true, size: 11..11
        cellphone size: 11..11, blank: true, nullable: true
        city blank: true, nullable: true
        externalId blank: true, nullable: true
        appSessionId blank: true, nullable: true
        avatarUrl nullable: true, blank: true, maxSize: 256
        verificationCode blank: true, nullable: true, maxSize: 16
    }

    static mapping = {
        table 'login_user'
        password column: '`password`'
    }

    String toString()
    {
        String alias

        if (department)
        {
            alias = "${department} ${fullName}"
        }
        else
        {
            alias = fullName
        }

        if (account)
        {
            "${account} ${alias}"
        }
        else
        {
            alias
        }
    }
}
